<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Admin
 * Date: 03.09.13
 * Time: 11:07
 * To change this template use File | Settings | File Templates.
 */

class OGrabber
{
    protected $_oBrowser = null;

    public function __construct()
    {
        $this->includeFile('AbstractParser');
        $this->includeFile('AbstractParserRow');
        $this->includeFile('Proxy');
        $this->includeFile('Browser');

        $this->_oBrowser = new Browser();
    }

    public function getRow( $parser, $row, $url = '' )
    {
        $this->includeFile('parsers/'.$parser);
        $this->includeFile($row);

        $oRow = new $row;
        $oParser = new $parser;

        $oParser->setParserRow($oRow);

        if($url)
            $oParser->setUrl($url);

        $html = $this->_oBrowser->get( $oParser->getUrl() );

        return $oParser->getRow($html);
    }

    public function getRowset( $parser, $row, $nextPage = false )
    {
        $this->includeFile('parsers/'.$parser);
        $this->includeFile($row);

        $oRow = new $row;
        $oParser = new $parser;

        $oParser->setParserRow($oRow);

        $url = @file_get_contents($parser.'.txt');
        if(!$url)
            $url = $oParser->getUrl();

        $html = $this->_oBrowser->get( $url );

        $aData = $oParser->getRowset($html);

        if(!empty($aData['page']))
            @file_put_contents($parser.'.txt', $aData['page']);
        else
            @file_put_contents($parser.'.txt', '');

        return $aData['rowset'];
    }

    public function includeFile($file)
    {
        $file = dirname(__FILE__) . '/grabber/' . $file . '.php';
        if (file_exists($file))
            require_once $file;
    }

}